package org.aeon.server.handler.Inbound;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.DefaultEventLoopGroup;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;
import lombok.extern.slf4j.Slf4j;
import org.aeon.annotation.PreventLoss;
import org.aeon.message.Message;
import org.aeon.service.Session;
import org.aeon.service.factory.SessionFactory;
import org.aeon.service.factory.UserServiceFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author: MissingAeon
 * @date: 2024/1/29 11:23
 * @description:
 */
@Slf4j
@ChannelHandler.Sharable
public class ChannelConnectHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        super.handlerAdded(ctx);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 只接受消息类
        if (msg instanceof Message) {
            super.channelRead(ctx, msg);
        } else {
            ctx.channel().close();
        }
    }

    // 当连接断开
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        offline(ctx);
        log.debug("{}断开", ctx.channel());
    }


    // 当异常时
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        offline(ctx);
        log.debug("{}异常断开：{}", ctx.channel(), cause.getMessage());
    }

    private void offline(ChannelHandlerContext ctx) {
        final Session session = SessionFactory.getSession();
        final Long userId = session.getUserId(ctx.channel());
        if (userId != null) {
            // messageReplay(ctx, userId);
            UserServiceFactory.getService().delTokens(userId);
            UserServiceFactory.getService().userOffline(userId);
        }
        session.unbind(ctx.channel());
    }

    @SuppressWarnings("unchecked")
    private void messageReplay(ChannelHandlerContext ctx, final Long userId) {
        // 获取未处理的消息
        final List<Message> messageList = (List<Message>) SessionFactory.getSession().getAttribute(ctx.channel(), "MessageList");
        if (messageList == null || messageList.isEmpty()) return;
        // 获取用户id
        // 重新储存消息
        messageList.forEach((message) -> UserServiceFactory.getService().addMessageToQueue(userId, message));
    }
}
